package com.open.capacity.employee.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.open.capacity.common.annotation.ApiIdempotent;
import com.open.capacity.common.auth.details.LoginAppUser;
import com.open.capacity.common.exception.controller.ControllerException;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.SysUser;
import com.open.capacity.common.util.SysUserUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.employee.model.EmployeeModel;
import com.open.capacity.employee.service.ExploitService;
import com.open.capacity.log.annotation.LogAnnotation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/exploit")
@Api(tags = "人员业绩")
public class ExploitController {


    @PostMapping("/test")
    public Result postTest(){
        return Result.succeed("好笑吗，甘霖凉");
    }


    @Autowired
    private ExploitService exploitService;

    /**
     * 当前登录用户 LoginAppUser
     *
     * @return
     * @throws ControllerException
     * @throws JsonProcessingException
     */
    @ApiOperation(value = "根据access_token当前登录用户")
    @GetMapping("/exploit/current")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public LoginAppUser getLoginAppUser() throws ControllerException {
        try {
            LoginAppUser loginUser = SysUserUtil.getLoginAppUser();
            return loginUser;
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }



    @PreAuthorize("hasAuthority('user:get/exploit/{id}')")
    @GetMapping("/exploit/{id}")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public SysUser findUserById(@PathVariable Long id) throws ControllerException {
        try {
            return exploitService.findById(id);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    /**
     * 管理后台修改用户
     *
     * @param sysUser
     * @throws JsonProcessingException
     */
    @PreAuthorize("hasAuthority('user:put/exploit/me')")
    @PutMapping("/exploit")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public void updateSysUser(@RequestBody SysUser sysUser) throws ControllerException {
        try {
            exploitService.updateSysUser(sysUser);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }



    /**
     * 用户查询
     * http://192.168.3.2:7000/exploit?access_token=3b45d059-601b-4c63-85f9-9d77128ee94d&start=0&length=10
     * @param params //  searchKey=username, searchValue=as
     * @return
     * @throws ControllerException
     */
    @PreAuthorize("hasAuthority('user:get/exploit')")
    @ApiOperation(value = "用户查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
    })
    @GetMapping("/exploit")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public PageResult<SysUser> findUsers(@RequestParam Map<String, Object> params) throws ControllerException {

        try {
            return exploitService.findUsers(params);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }




    /**
     * 修改用户状态
     * @param params
     * @return
     * @throws ControllerException
     * @author gitgeek
     */
    @ApiOperation(value = "修改用户状态")
    @GetMapping("/exploit/updateEnabled")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "enabled", value = "是否启用", required = true, dataType = "Boolean")
    })
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    @PreAuthorize("hasAnyAuthority('user:get/exploit/updateEnabled' ,'user:put/exploit/me')")
    public Result updateEnabled(@RequestParam Map<String, Object> params) throws ControllerException {
        try {
            Long id = MapUtils.getLong(params, "id");
            if (id == 1277137734524300032L) {
                return Result.failed("超级管理员不给予修改");
            }
            return exploitService.updateEnabled(params);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }




    /**
     * 新增or更新
     * @param sysUser
     * @return
     * @throws ControllerException
     */
    @PostMapping("/exploit/saveOrUpdate")
    @PreAuthorize("hasAnyAuthority('user:post/users/saveOrUpdate')")
    @LogAnnotation(module = "employee-center", recordRequestParam = false)
    public Result saveOrUpdate(@RequestBody SysUser sysUser) throws ControllerException {
        try {
            return exploitService.saveOrUpdate(sysUser);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        }
    }

    /**
     * 导出数据
     *
     * @return
     * @throws ControllerException
     */
    @PostMapping("/exploit/exportUser")
    @PreAuthorize("hasAuthority('user:post/exploit/exportUser')")
    public void exportUser(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws ControllerException {
        try {
            List<EmployeeModel> result = exploitService.findAllUsers(params);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");
            @Cleanup OutputStream ouputStream = null;
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户导出", "用户"),
                    EmployeeModel.class, result);
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (ServiceException e) {
            throw new ControllerException(e);
        } catch (IOException e) {
            throw new ControllerException(e);
        }

    }
    /**
     * 后台管理删除角色
     * delete /role/1
     * @param id
     * @throws ControllerException
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "后台管理删除用户")
    @PreAuthorize("hasAuthority('user:post/users/saveOrUpdate')")
    @LogAnnotation(module="employee-center",recordRequestParam=false)
    public Result deleteRole(@PathVariable Long id) throws ControllerException {
        try {
            if (id == 1277137734524300032L){
                return Result.failed("管理员不可以删除");
            }
            exploitService.deleteUser(id);
            return Result.succeed("操作成功");
        }catch (Exception e){
            throw new ControllerException(e);
        }
    }

    /**
     * 测试幂等接口
     * @param sysUser
     * @return
     * @throws ControllerException
     */
    @PostMapping("/exploit/save")
    @ApiIdempotent
    public Result save(@RequestBody SysUser sysUser) throws ControllerException {
        try {
            return exploitService.saveOrUpdate(sysUser);
        } catch (ServiceException e) {
            log.error("执行" + this.getClass().getSimpleName() + ":" + new Exception().getStackTrace()[0].getMethodName());
            throw new ControllerException(e);
        }
    }


}

